package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;

import com.woyao.core.model.GetMyMarkResponse;
import com.woyao.core.model.MarkSummary;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class MyMarkActivity extends AppCompatActivity {

    private List<MarkSummary> items = new ArrayList<MarkSummary>();
    private MarkAdapter allAdapter;
    private RecyclerView alllist = null;
    LinearLayoutManager allLayoutManager = null;
    String content = "";

    ProgressDialog progressDialog;

    private String keyword = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_relation);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout


        Intent intent = getIntent();

        keyword = intent.getStringExtra("keyword") ;
        if ( keyword == null )
            keyword = "";


        alllist = (RecyclerView)findViewById(R.id.items);
        allLayoutManager = new LinearLayoutManager(this);
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));


        content = intent.getStringExtra("content");
        if (content == null){
            content = "";
        }
        loadData( content);

        this.registerForContextMenu(alllist);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }


    private AsyncTask<Void,Void, GetMyMarkResponse> task = null;
    private void loadData( final String kw){
        if(task != null)return;

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        task =new AsyncTask<Void, Void, GetMyMarkResponse>() {
            @Override
            protected GetMyMarkResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyMarkResponse> responseCall = svc.getMyMark(userId,kw);
                try {
                    GetMyMarkResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyMarkResponse response) {
                progressDialog.dismiss();

                if (response.isSuccess()) {
                    render(response);
                }else{
                    Dialog alertDialog = new AlertDialog.Builder(MyMarkActivity.this).
                            setTitle("信息").
                            setMessage(response.getMessage()).
                            setIcon(R.drawable.ic_launcher).
                            setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (response.getCondition().equals("charge")){
                                        Intent intent = new Intent();
                                        intent.setClass( MyMarkActivity.this, MoneyActivity.class);
                                        startActivity(intent);
                                    }
                                }
                            }).
                            create();
                    alertDialog.show();
                }
                task = null;
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }
    private void render(GetMyMarkResponse response){

        items = response.getContent();
        this.setTitle( "我的关注：" + items.size() );

        if (content.equals("iapply")){
            this.setTitle( "我想合作：" + items.size() );
        }

        if (content.equals("applyme")){
            this.setTitle( "想合作我：" + items.size() );
        }

        allAdapter = new MarkAdapter(this,  items );

        allAdapter.setChangedHandler(new MarkAdapter.Changed() {
            @Override
            public void view(MarkSummary r) {
                getIt(r.getId() );
            }
        });



        alllist.setAdapter(allAdapter);

    }

    private void getIt( final Integer curid ){
        Intent intent = new Intent();
        intent.setClass(MyMarkActivity.this, ChanceViewActivity.class);
        intent.putExtra("pid", curid  );
//        intent.setClass(MyRelationActivity.this, TalkActivity.class);
//        intent.putExtra("mid", curid  );
        startActivity(intent);

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
